package cn.com.xinjinfu.pdoulcProduct.activity.recharge;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.user.ActCertification;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.ActRechargeBean;
import cn.com.xinjinfu.pdoulcProduct.entity.BanksCardBean;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.BankImgUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.EditTextUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.ReloadUserInfo;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.BaseHelper;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.Constants;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.MobileSecurePayer;

/**
 * 充值
 * Created by android-adt on 2016/1/5.
 */
public class ActRechargeBinding extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    protected static final String TAG = "NumberAdapter";
    private Button mAffirmBuy;
    private double balance;
    private Dialog dg;
    private LinearLayout mNoMoneyHint;
    private RelativeLayout ll_have_bank;

    private TextView mBankcart, tv_account_balance, tv_error_hint, tv_bank_name, tv_bankcart_num, textView01;
    ;
    private EditText tv_carnum;
    private EditText et_recharge_money;
    private ImageView img_bankcard;
    private ListView lv;
    private PopupWindow pw;
    private BankCartAdapter adapter;

    //银行图标，名称和卡号
    private String mBank;
    private String mBankCode;
    private User user;
    private BanksCardBean.SupportBanks supportBanks;

    private int m, y;
    private RequestQueue requen;
    private List<BanksCardBean.SupportBanks> banksList;
    private ActRechargeBean actRechargeBean;
    private ActRechargeBean.Jsonresult jsonresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_recharge);
        //初始化头布局
        TitleManager.showTitle(this, "充值", "");
        user = AccountManager.getInstance().getUser();
        Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        balance = bundle.getDouble("balance");
        initViews();
        requen = Volley.newRequestQueue(this);

    }

    private void initViews() {
        //隐藏的银行框
        mNoMoneyHint = (LinearLayout) findViewById(R.id.ll_nomoney_hint);
        ll_have_bank = (RelativeLayout) findViewById(R.id.ll_have_bank);
        //已经绑定的银行卡
        tv_bank_name = (TextView) findViewById(R.id.tv_bank_name);
        tv_bankcart_num = (TextView) findViewById(R.id.tv_bankcart_num);
        textView01 = (TextView) findViewById(R.id.textView01);
        img_bankcard = (ImageView) findViewById(R.id.img_bankcard);
        //选择银行卡列表
        mBankcart = (TextView) findViewById(R.id.tv_bankcart);
        findViewById(R.id.rl_select_number).setOnClickListener(this);
        tv_carnum = (EditText) findViewById(R.id.tv_carnum);

        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        tv_account_balance = (TextView) findViewById(R.id.tv_account_balance);
        tv_account_balance.setText(TextViewUtil.getSumLength(balance));
        et_recharge_money = (EditText) findViewById(R.id.et_recharge_money);
        EditTextUtil.setPricePoint(et_recharge_money);
        et_recharge_money.addTextChangedListener(mTextWatcher);
        mAffirmBuy = (Button) findViewById(R.id.affirm_buy);
        mAffirmBuy.setOnClickListener(this);

        if (user != null)
            if (user.getBank() == -1) {
                //已经绑定过银行卡
                ll_have_bank.setVisibility(View.VISIBLE);
                mNoMoneyHint.setVisibility(View.GONE);
                tv_bank_name.setText(user.getBank_name());
                int x = new BankImgUtils().mBank(true, user.getBank_code());
                tv_bank_name.setBackgroundColor(x);
                String id = user.getAccount();
                String show_id = "**** **** **** " + id.substring(id.length() - 4);
                tv_bankcart_num.setText(show_id);
                img_bankcard.setImageResource(new BankImgUtils().mBank(false, user.getBank_code()));
                if (user.getBank_status().equals("0")) {
                    textView01.setText("*每笔限额" + NumberFormat.getInstance().format(user.getSingle_amt() / 10000) +
                            "万元，每日限额" + NumberFormat.getInstance().format(user.getDay_amt() / 10000) + "万元");
                } else if (user.getBank_status().equals("2")) {
                    textView01.setText(user.getBank_name()+"维护中，暂无法支付\n可在PC端以网银充值方式进行支付");
                }
            } else {
                mNoMoneyHint.setVisibility(View.VISIBLE);     //第一次绑卡
                ll_have_bank.setVisibility(View.GONE);
            }
    }

    /**
     * 支付 网络请求
     */
    private void loginRequest() {
        if (!DataHandler.isNetworkConnected(this)) {
            ToastManager.show(this, "请检查网络连接");
            return;
        }
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1301");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("rechargeAmount", et_recharge_money.getText().toString());
            if (user.getBank() == -1) {
                parameters.put("rechargeType", "1");
                parameters.put("card_no", user.getAccount());
                parameters.put("bankCode", user.getBank_code());
                parameters.put("single_amt", user.getSingle_amt() + "");
                parameters.put("day_amt", user.getDay_amt() + "");
                parameters.put("month_amt", user.getMonth_amt() + "");
            } else {
                parameters.put("rechargeType", "0");
                parameters.put("card_no", tv_carnum.getText().toString());
                parameters.put("bankCode", mBankCode);
                parameters.put("single_amt", supportBanks.getSingle_amt() + "");
                parameters.put("day_amt", supportBanks.getDay_amt() + "");
                parameters.put("month_amt", supportBanks.getMonth_amt() + "");
            }
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            dg.dismiss();
            actRechargeBean = JSON.parseObject(jobj.toString(), ActRechargeBean.class);
            if (actRechargeBean.getCode() == -1) {
                jsonresult = actRechargeBean.getJsonresult();
                JSONObject jsonresult0 = null;
                String acct_name = strUTF8Name(jsonresult.getAcct_name());
                try {
                    jsonresult0 = jobj.getJSONObject("jsonresult");
                    jsonresult0.put("acct_name", acct_name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                L.d("跳转到连连支付平台");
                MobileSecurePayer msp = new MobileSecurePayer();
                boolean bRet = msp.pay(jsonresult0.toString(), mHandler,
                        Constants.RQF_PAY, ActRechargeBinding.this, false);
            } else {
                tv_error_hint.setText(actRechargeBean.getMsg());
            }
        }
    };

    /**
     * 银行卡列表
     */
    private void loginBankcardRequest() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        final Map<String, String> parameters = DataHandler.getParameters("1302");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, BankListRespon, error);
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ActRechargeBinding.this, error);
        }
    };
    private Response.Listener<JSONObject> BankListRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i("BankListRespon=============" + jobj.toString());
            dg.dismiss();
            BanksCardBean banksCardBean = JSON.parseObject(jobj.toString(), BanksCardBean.class);
            banksList = banksCardBean.getSupportBanks();
            showBankcardDialog();
        }
    };

    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");
                        String no_order = objContent.optString("no_order");
                        String result_pay = objContent.optString("result_pay");
                        String money_order = objContent.optString("money_order");
                        try {
                            objContent.put("ret_msg", "");
                            objContent.put("ret_code", "");
                            objContent.put("agreementno", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // TODO 先判断状态码，状态码为 成功或处理中 的需要 验签
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            String resulPay = objContent.optString("result_pay");
                            if (Constants.RESULT_PAY_SUCCESS
                                    .equalsIgnoreCase(resulPay)) {
                                // TODO 支付成功后续处理
                                dg = UIManager.getLoadingDialog(ActRechargeBinding.this);
                                dg.setCanceledOnTouchOutside(false);
                                dg.show();
                                final Map<String, String> parameters = DataHandler.getParameters("1308");
                                parameters.put("no_order", no_order);
                                parameters.put("result_pay", result_pay);
                                parameters.put("res_data", objContent.toString());
                                parameters.put("money_order", money_order);
                                /**
                                 * 延时1.3秒
                                 * 方法1，定时器
                                 * 方法2，子线程
                                 */
//                                TimerTask task = new TimerTask() {
//                                    public void run() {
//                                        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon1, error);
//                                        requen.add(request);
//                                    }
//                                };
//                                Timer timer = new Timer();
//                                timer.schedule(task, 1300);

                                new Handler(new Handler.Callback() {
                                    @Override
                                    public boolean handleMessage(Message msg) {
                                        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon1, error);
                                        request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                                        requen.add(request);
                                        return true;
                                    }
                                }).sendEmptyMessageDelayed(0, 1300);
                            } else {
                                UIManager.showSuccessDilog(ActRechargeBinding.this, R.drawable.img_fail, 1, "充值失败\n" + retMsg, "返回我的P兜", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        finish();
                                    }
                                });
                            }
                        } else {
                            UIManager.showSuccessDilog(ActRechargeBinding.this, R.drawable.img_fail, 1, "充值失败\n" + retMsg, "返回我的P兜", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    finish();
                                }
                            });
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    private Response.Listener<JSONObject> succeedRespon1 = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("-----------充值验签结果-----------------" + jobj.toString());
            dg.dismiss();
            /****延时1秒***刷新user****/
            new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    new ReloadUserInfo(ActRechargeBinding.this).userRequest();
                    return true;
                }
            }).sendEmptyMessageDelayed(0, 1000);

            if (JSONManager.getString(jobj, "result").equals("SUCCESS")) {
                UIManager.showSuccessDilog(ActRechargeBinding.this, R.drawable.img_douhappy, 0, "充值成功", "返回我的P兜", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Message msg = new Message();
                        msg.what = 101;
                        handler.sendMessage(msg);
                    }
                });
            }else {
                UIManager.showSuccessDilog(ActRechargeBinding.this, R.drawable.img_fail, 1, "充值处理中", "返回我的P兜", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 101:
                    dg.show();
                    TimerTask task = new TimerTask() {
                        public void run() {
                            dg.dismiss();
                            finish();
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, 900);
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        if (!NewUtil.checkClick(v.getId())) return;
        switch (v.getId()) {
            case R.id.affirm_buy:
                /** *  还要在此判断是否实名认证  ***/
                if (user.getCurrUser().getIdNumber() == null) {
                    Intent intent2 = new Intent();
                    intent2.putExtra("cer_style_falg", 1);
                    intent2.setClass(this, ActCertification.class);
                    startActivity(intent2);
                    ToastManager.showShort(this, "请先实名认证！");
                } else {
                    if (user.getBank() == 0) {
                        request();
                        if (m == 1 && y == 1) {
                            loginRequest();
                        }
                    } else {
                        if (user.getBank_status().equals("2")) {
                            Toast.makeText(mContext, user.getBank_name() + "维护中，暂无法支付\n可在PC端以网银充值方式进行支付", Toast.LENGTH_LONG).show();
                        }else {
                            loginRequest();
                        }
                    }
                }
                break;
            case R.id.rl_select_number:
                /**银行卡列表网络请求**/
                loginBankcardRequest();
                break;
            default:
                break;
        }
    }

    //判断输入框
    private void request() {

        String s = et_recharge_money.getText().toString();
        if (s.equals("") || s.equals("0")) {
            et_recharge_money.requestFocus();
            tv_error_hint.setText("您输入的金额有误，请重新输入!");
            m = 0;
            return;
        }
        m = 1;
        s = tv_carnum.getText().toString();
        if (s.equals("")) {
            tv_carnum.requestFocus();
            tv_error_hint.setText("请填写您的银行卡账号");
            y = 0;
            return;
        }
        y = 1;

    }


    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            tv_error_hint.setText("");
            String recharge_money = et_recharge_money.getText().toString();
            if (recharge_money.equals("")) {

            }
        }
    };

    /**
     * URLdecode姓名转换成utf——8
     */
    public String strUTF8Name(String URLdecode) {
        String strUTF8 = null;
        try {
            strUTF8 = URLDecoder.decode(URLdecode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        L.d("=====================================" + strUTF8);
        return strUTF8;
    }

    /**
     * 选择银行的小窗体PopupWindow
     */
    private void showBankcardDialog() {
        // 先把ListView创建出来
        lv = new ListView(this);
        lv.setBackgroundResource(R.drawable.listview_background);
        lv.setDividerHeight(1);
        // 隐藏滚动条
        lv.setVerticalScrollBarEnabled(false);
        adapter = new BankCartAdapter();
        L.i("banksList=============" + banksList.toString());
        adapter.setList(banksList);
        adapter.notifyDataSetChanged();
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        lv.setOnItemClickListener(this);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）
        int height = metric.heightPixels - NewUtil.dip2px(this,274);
        pw = new PopupWindow(lv, width, height);
        // 设置点击外部 可以被关闭
        pw.setOutsideTouchable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        // 指定popupWindow允许获得焦点
        pw.setFocusable(true);
        pw.showAtLocation(mBankcart, Gravity.BOTTOM, 0, 0);
    }

    class BankCartAdapter extends BaseAdapter {

        private List<BanksCardBean.SupportBanks> banksList;

        public void setList(List<BanksCardBean.SupportBanks> banksList) {
            this.banksList = banksList;
        }

        @Override
        public int getCount() {
            return banksList == null ? 0 : banksList.size();
        }

        @Override
        public Object getItem(int position) {
            return banksList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(ActRechargeBinding.this, R.layout.bankcart_item, null);
                holder.tvNumber = (TextView) convertView.findViewById(R.id.tv_number);
                holder.bank_info = (TextView) convertView.findViewById(R.id.bank_info);
                holder.imgBankcard = (ImageView) convertView.findViewById(R.id.img_bankcard);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            BanksCardBean.SupportBanks supportBanks = banksList.get(position);
            if (banksList != null) {
                holder.tvNumber.setText(supportBanks.getBank_name());
                int x = new BankImgUtils().mBank(false, supportBanks.getBank_code());
                holder.imgBankcard.setImageResource(x);

                if (supportBanks.getBank_status().equals("2")) {
                    holder.bank_info.setText("该银行在维护中，暂不支持充值");
                } else {
                    holder.bank_info.setText("*单笔限额" + NumberFormat.getInstance().format(supportBanks.getSingle_amt() / 10000) +
                            "万元，每日限额" + NumberFormat.getInstance().format(supportBanks.getDay_amt() / 10000) + "万元");
                }
            }

            return convertView;
        }

        class ViewHolder {
            public TextView tvNumber;
            public ImageView imgBankcard;
            public TextView bank_info;
        }
    }

    /**
     * 取出银行名称数据, 显示在输入框中
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        supportBanks = banksList.get(position);
        if (supportBanks.getBank_status().equals("2")) {
            return;
        } else {
            mBank = supportBanks.getBank_name();
            mBankCode = supportBanks.getBank_code();
            pw.dismiss();
            /**
             * 选择好银行后的提示框 dialog
             */
            UIManager.showBankInfo(this, supportBanks, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    findViewById(R.id.rl_account_num).setVisibility(View.VISIBLE);
                    mBankcart.setText(mBank);
                    mBankcart.setTextColor(0xff333333);
                }
            });
        }
    }

}